package com.dge.common.utils

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonArray
import com.google.gson.JsonNull
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.hjq.gson.factory.GsonFactory
import com.dge.common.common.AppConfig

object GsonUtils {
    val gson: Gson = if (AppConfig.isDebug()) {
        GsonBuilder().disableHtmlEscaping().create() //debug版不用容错框架，在测试阶段把暴露出的问题解决
    } else {
        GsonFactory.newGsonBuilder().disableHtmlEscaping().create() //release版使用GsonFactory容错框架，防止潜在的解析崩溃
    }

    @JvmStatic
    fun removeNullsFromJson(jsonObject: JsonObject) {
        val iterator = jsonObject.keySet().iterator()
        while (iterator.hasNext()) {
            val key = iterator.next()
            when (val json = jsonObject[key]) {
                is JsonObject -> removeNullsFromJson(json)
                is JsonArray -> dealWithJsonArray(json)
                is JsonNull -> iterator.remove()
            }
        }
    }

    @JvmStatic
    fun dealWithJsonArray(jsonArray: JsonArray) {
        val iterator = jsonArray.iterator()
        while (iterator.hasNext()) {
            when (val json = iterator.next()) {
                is JsonObject -> removeNullsFromJson(json)
                is JsonArray -> dealWithJsonArray(jsonArray)
                is JsonNull -> iterator.remove()
            }
        }
    }

    fun toJson(src: Any, removeNullFiled: Boolean = true): String {
        return if (removeNullFiled) {
            val oldJson = gson.toJson(src)
            val jsonObject = JsonParser.parseString(oldJson).asJsonObject
            removeNullsFromJson(jsonObject)
            jsonObject.toString()
        } else {
            gson.toJson(src)
        }
    }
}
